<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="HTML5," />










<meta name="description" content="前言这段时间一这被很多事情所牵绕，没能好好的写博客学习，感觉很难受，但所幸事情大都告一段落了。对于 Web Workers 的学习主要是由于在上这周面试的时候，面试的一个大佬，问到了这个问题，而我只知道它有这个东西，但具体如何实现它，以及它的使用场景我不是很清楚。因此这两天花了些时间看了不少文章，来总结一下。 一、Web Workers是什么 Web Worker为Web内容在后台线程中运行脚本提">
<meta name="keywords" content="HTML5">
<meta property="og:type" content="article">
<meta property="og:title" content="初探 HTML5 Web Workers">
<meta property="og:url" content="http://srtian96.gitee.io/blog/2018/07/21/初探 HTML5 Web Workers/index.html">
<meta property="og:site_name" content="Srtian&#39;Blog">
<meta property="og:description" content="前言这段时间一这被很多事情所牵绕，没能好好的写博客学习，感觉很难受，但所幸事情大都告一段落了。对于 Web Workers 的学习主要是由于在上这周面试的时候，面试的一个大佬，问到了这个问题，而我只知道它有这个东西，但具体如何实现它，以及它的使用场景我不是很清楚。因此这两天花了些时间看了不少文章，来总结一下。 一、Web Workers是什么 Web Worker为Web内容在后台线程中运行脚本提">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://qiutc.me/img/section-webworker-1.png">
<meta property="og:updated_time" content="2018-07-21T06:09:05.043Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="初探 HTML5 Web Workers">
<meta name="twitter:description" content="前言这段时间一这被很多事情所牵绕，没能好好的写博客学习，感觉很难受，但所幸事情大都告一段落了。对于 Web Workers 的学习主要是由于在上这周面试的时候，面试的一个大佬，问到了这个问题，而我只知道它有这个东西，但具体如何实现它，以及它的使用场景我不是很清楚。因此这两天花了些时间看了不少文章，来总结一下。 一、Web Workers是什么 Web Worker为Web内容在后台线程中运行脚本提">
<meta name="twitter:image" content="https://qiutc.me/img/section-webworker-1.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://srtian96.gitee.io/blog/2018/07/21/初探 HTML5 Web Workers/"/>





  <title>初探 HTML5 Web Workers | Srtian'Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Srtian'Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">It's better to burn out than to fade away</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/blog/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://srtian96.gitee.io/blog/blog/2018/07/21/初探 HTML5 Web Workers/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Srtian">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Srtian'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">初探 HTML5 Web Workers</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-07-21T13:35:33+08:00">
                2018-07-21
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/JavaScript/" itemprop="url" rel="index">
                    <span itemprop="name">JavaScript</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2,253
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  9
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><p>这段时间一这被很多事情所牵绕，没能好好的写博客学习，感觉很难受，但所幸事情大都告一段落了。对于 Web Workers 的学习主要是由于在上这周面试的时候，面试的一个大佬，问到了这个问题，而我只知道它有这个东西，但具体如何实现它，以及它的使用场景我不是很清楚。因此这两天花了些时间看了不少文章，来总结一下。</p>
<h3 id="一、Web-Workers是什么"><a href="#一、Web-Workers是什么" class="headerlink" title="一、Web Workers是什么"></a>一、Web Workers是什么</h3><blockquote>
<p>Web Worker为Web内容在后台线程中运行脚本提供了一种简单的方法。线程可以执行任务而不干扰用户界面。此外，他们可以使用XMLHttpRequest执行 I/O (尽管responseXML和通道属性总是为空)。一旦创建， 一个worker 可以将消息发送到创建它的JavaScript代码, 通过将消息发布到该代码指定的事件处理程序 (反之亦然)。 —— MDN</p>
</blockquote>
<p>众所周知，JavaScript是单线程的编程语言，也就是说，当我们在页面中进行一个较为耗时的计算的JavaScript代码时，在这段代码执行完毕之前，页面是无法响应用户操作的。也正是出于这个原因，HTML5为我们提供了 Web Workers 以解决这种问题，当我们需要在JavaScript中来进行耗时的计算或诸如此类的问题时，我们可以使用 Web Workers 在浏览器的后台启动一个独里的 Worker 线程来专门负责这段代码的运行，而不会阻碍后面代码的运行。</p>
<h3 id="二、Web-Workers的使用"><a href="#二、Web-Workers的使用" class="headerlink" title="二、Web Workers的使用"></a>二、Web Workers的使用</h3><h4 id="1-实例化一个-Worker"><a href="#1-实例化一个-Worker" class="headerlink" title="1. 实例化一个 Worker"></a>1. 实例化一个 Worker</h4><p>实例化运行一个 Worker 很简单，我们只需要 new 一个 Worker 全局对象即可。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> worker = <span class="keyword">new</span> Worker(<span class="string">'./worker.js'</span>)</span><br></pre></td></tr></table></figure>
<p>它接受一个 filepathname String 参数，用于指定 Worker 脚本文件的路径。然后我们就可以在 worker.js 中写下一些代码:</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="string">'my_WOEKER:'</span>, <span class="string">'srtian'</span>)</span><br></pre></td></tr></table></figure>
<p>另外，通过URL.createObjectURL()创建URL对象，也可以实现创建内嵌的worker:</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> myTask = <span class="string">`</span></span><br><span class="line"><span class="string">    var i = 0;</span></span><br><span class="line"><span class="string">    var timedCount = () =&gt; &#123;</span></span><br><span class="line"><span class="string">        i = i+1;</span></span><br><span class="line"><span class="string">        postMessage(i);</span></span><br><span class="line"><span class="string">        setTimeout(timedCount, 1000);</span></span><br><span class="line"><span class="string">    &#125;</span></span><br><span class="line"><span class="string">    timedCount();</span></span><br><span class="line"><span class="string">`</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> myblob = <span class="keyword">new</span> Blob([myTask]);</span><br><span class="line"><span class="keyword">var</span> myWorker = <span class="keyword">new</span> Worker(<span class="built_in">window</span>.URL.createObjectURL(myblob));</span><br></pre></td></tr></table></figure>
<blockquote>
<p>需要注意的是，传入 Worker 构造函数的参数 URI 必须遵循同源策略。</p>
</blockquote>
<p>此外因为Worker线程的创建的是异步的，所以主线程代码不会阻塞在这里等待 worker 线程去加载、执行指定的脚本文件，而是会立即向下继续执行后面代码这点也需要注意。</p>
<h4 id="2-数据通信"><a href="#2-数据通信" class="headerlink" title="2. 数据通信"></a>2. 数据通信</h4><p>当我们实例化一个 Worker 线程后，Worker不会相互，或者与主程序共享任何作用域或资源——那会将所有的多线程编程的噩梦带到我们面前——取而代之的是一种连接它们的基本事件消息机制。因此他们需要通过基于事件监听机制的message来进行通信，我们在new Worker()后悔返回一个实例对象，它包含了一个postMessage的方法，我们可以通过调用这个方法来给worker线程传递信息，我们也可以给这个对象监听事件，从而在worker线程中出发事件通信的时候能接收到数据。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> worker = <span class="keyword">new</span> worker(<span class="string">'./worker.js'</span>)</span><br><span class="line">worker.addEventListener(<span class="string">'message'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">e</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'worker receive:'</span>, e.data )</span><br><span class="line">&#125;</span><br><span class="line">worker.postMessage(<span class="string">'hello worker,this is main.js'</span>)</span><br></pre></td></tr></table></figure>
<p>然后在worker.js这个脚本中，我们就可以调用全局函数postMessage和全局的onmessage赋值来发送和监听数据和事件了。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 监听事件</span></span><br><span class="line">onmessage = <span class="function"><span class="keyword">function</span> (<span class="params">e</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'WORKER RECEIVE：'</span>, e.data);</span><br><span class="line">  <span class="comment">// 发送数据事件</span></span><br><span class="line">  postMessage(<span class="string">'Hello, this is worker.js'</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>需要注意的是 worker 支持 JavaScript 中所有类型的数据传递，可以传递一个 Object 数据；但这里的数据传递（主要是 Object 类型）并不是共享，而是复制。发送端的数据和接收端的数据是复制而来，并不指向同一个对象，此外这里的复制不是简单的拷贝，而是通过两端的序列化/解序列化来实现的，一般来说浏览器会通过 JSON 编码/解码；当然，这里的更多细节部分会由浏览器来处理，我们并不需要关心这些，只需要明白两端的数据是复制而来，互相独立的就行了。</p>
<h4 id="3-错误处理机制"><a href="#3-错误处理机制" class="headerlink" title="3. 错误处理机制"></a>3. 错误处理机制</h4><p>当 worker 出现运行中错误时，它的 onerror 事件处理函数会被调用。它会收到一个扩展了 ErrorEvent 接口的名为 error的事件。</p>
<p>该事件不会冒泡并且可以被取消；为了防止触发默认动作，worker 可以调用错误事件的 preventDefault() 方法。</p>
<p>错误事件有以下三个用户关心的字段：</p>
<ul>
<li>message: 可读性良好的错误消息。</li>
<li>filename: 发生错误的脚本文件名。</li>
<li>lineno: 发生错误时所在脚本文件的行号。 </li>
</ul>
<p>实际操作如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> worker = <span class="keyword">new</span> Worker(<span class="string">'./worker.js'</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 监听消息事件</span></span><br><span class="line">worker.addEventListener(<span class="string">'message'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">e</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'MAIN RECEIVE： '</span>, e.data);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">// 也可以使用 onMessage 来监听事件：</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 监听 error 事件</span></span><br><span class="line">worker.addEventListener(<span class="string">'error'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">e</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'MAIN ERROR：'</span>, e);</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'MAIN ERROR：'</span>, <span class="string">'filename:'</span> + e.filename + <span class="string">'---message:'</span> + e.message + <span class="string">'---lineno:'</span> + e.lineno);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 触发事件，传递信息给 Worker</span></span><br><span class="line">worker.postMessage(&#123;</span><br><span class="line">  m: <span class="string">'Hello Worker, this is main.js'</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h4 id="4-终止-Worker"><a href="#4-终止-Worker" class="headerlink" title="4. 终止 Worker"></a>4. 终止 Worker</h4><p>当我们在不需要 Worker 继续运行时，我就需要终止掉这个线程，这时候我们就可以调用 worker 的 terminate 方法:</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">worker.terminate()</span><br></pre></td></tr></table></figure>
<p>worker 线程会被立即杀死，不会有任何机会让它完成自己的操作或清理工作。</p>
<p>而在worker线程中，workers 也可以调用自己的 close  方法进行关闭：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">close()</span><br></pre></td></tr></table></figure>
<h3 id="三-Web-Workers的兼容"><a href="#三-Web-Workers的兼容" class="headerlink" title="三. Web Workers的兼容"></a>三. Web Workers的兼容</h3><p>由于Web Workers是HTML5所提供的，因此从兼容性上来说，还是需要注意的。总的兼容情况如下图所示：<br><img src="https://qiutc.me/img/section-webworker-1.png" alt="image"><br>图片来源：<a href="https://caniuse.com/#feat=webworkers" target="_blank" rel="noopener">https://caniuse.com/#feat=webworkers</a></p>
<p>我们可以看到，虽然web worker很不错，但如果我们的代码执行在较老的浏览器中时，是缺乏支持的。但由于worker是一个API而不是语法，因此我门还是可以去填补它的。</p>
<p>这一块的详情可以去看——《你不知道的JavaScript中卷》关于 web worker 的那一节。</p>
<h3 id="四、Web-Workers支持的JavaScript特性"><a href="#四、Web-Workers支持的JavaScript特性" class="headerlink" title="四、Web Workers支持的JavaScript特性"></a>四、Web Workers支持的JavaScript特性</h3><p>由于在 Worker 线程的运行环境中没有 window 全局对象，也无法访问 DOM 对象，所以一般来说我们在这只能执行纯JavaScript的计算操作，当然1我们那：</p>
<ul>
<li>setTimeout()， clearTimeout()， setInterval()， clearInterval()：有了设计个函数，就可以在 Worker 线程中执行定时操作了；</li>
<li>XMLHttpRequest 对象：意味着我们可以在 Worker 线程中执行 ajax 请求；</li>
<li>navigator 对象：可以获取到 ppName，appVersion，platform，userAgent 等信息；</li>
<li>location 对象（只读）：可以获取到有关当前 URL 的信息；</li>
<li>应用缓存</li>
<li>使用 importScripts() 引入外部 script</li>
<li>创建其他的 Web Worker</li>
</ul>
<h3 id="五、Web-Worker-的实践"><a href="#五、Web-Worker-的实践" class="headerlink" title="五、Web Worker 的实践"></a>五、Web Worker 的实践</h3><p>总的来说，Web Worker为我们带来了强大的计算能力，我们可以加载一个JavaScript进行大量的复杂计算，而用不挂起主进程。并通过postMessage，onmessage进行通信，这也解决了大量计算对UI渲染的阻塞问题。</p>
<h4 id="应用场景"><a href="#应用场景" class="headerlink" title="应用场景"></a>应用场景</h4><h5 id="1、数学运算"><a href="#1、数学运算" class="headerlink" title="1、数学运算"></a>1、数学运算</h5><p>Web Worker最简单的应用应该就是用来进行后台计算了，这对CPU密集型的场景再适合不过了。</p>
<h5 id="2、图像处理"><a href="#2、图像处理" class="headerlink" title="2、图像处理"></a>2、图像处理</h5><p>通过使用从 canvas 中获取的数据，可以把图像分割成几个不同的区域并且把它们推送给并行的不同Workers来做计算，对图像进行像素级的处理，再把处理完成的图像数据返回给主页面。</p>
<h5 id="3、大数据的处理"><a href="#3、大数据的处理" class="headerlink" title="3、大数据的处理"></a>3、大数据的处理</h5><p>目前mvvm框架越来越普及，基于数据驱动的开发模式也越愈发流行，未来大数据的处理也可能转向到前台，因此我们将大数据的处理交给在Web Worker也是很好的。</p>
<h5 id="4-数据预处理"><a href="#4-数据预处理" class="headerlink" title="4. 数据预处理"></a>4. 数据预处理</h5><p>为优化的网站或 web 应用的数据加载时长，我们可以使用 Web Worker 预先获取一些数据，存储起来以备后续使用，因为它绝不会影响应用的 UI 体验。</p>
<h5 id="5-大量的-ajax-请求或者网络服务轮询"><a href="#5-大量的-ajax-请求或者网络服务轮询" class="headerlink" title="5. 大量的 ajax 请求或者网络服务轮询"></a>5. 大量的 ajax 请求或者网络服务轮询</h5><p>由于在主线程中每启动一个XMLHttpRequest请求都会消耗资源，虽然在请求过程中浏览器另外开了一个线程，但是在交互过程中还是需要消耗主线程资源；而使用worker则不会过多占用主线程，只是启动worker过程时比较耗资源。</p>
<p>参考资料：</p>
<ol>
<li>《你不知道的JavaScript中卷》</li>
<li><a href="https://juejin.im/post/59c1b3645188250ea1502e46" target="_blank" rel="noopener">https://juejin.im/post/59c1b3645188250ea1502e46</a></li>
<li><a href="https://developer.mozilla.org/zh-CN/docs/Web/API/Web_Workers_API/Using_web_workers" target="_blank" rel="noopener">https://developer.mozilla.org/zh-CN/docs/Web/API/Web_Workers_API/Using_web_workers</a></li>
<li><a href="https://qiutc.me/post/the-multithread-in-javascript-web-worker.html" target="_blank" rel="noopener">https://qiutc.me/post/the-multithread-in-javascript-web-worker.html</a></li>
<li><a href="https://juejin.im/post/5a90233bf265da4e92683de3" target="_blank" rel="noopener">https://juejin.im/post/5a90233bf265da4e92683de3</a></li>
</ol>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/HTML5/" rel="tag"># HTML5</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/07/04/Node.js模块之Buffer/" rel="next" title="Node.js模块之Buffer">
                <i class="fa fa-chevron-left"></i> Node.js模块之Buffer
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/07/26/Node.js爬虫初体验/" rel="prev" title="Node.js 爬虫初体验">
                Node.js 爬虫初体验 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpg"
                alt="Srtian" />
            
              <p class="site-author-name" itemprop="name">Srtian</p>
              <p class="site-description motion-element" itemprop="description">JUST DO IT.</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">59</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">37</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/srtian96" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="shenruotian@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#一、Web-Workers是什么"><span class="nav-number">2.</span> <span class="nav-text">一、Web Workers是什么</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#二、Web-Workers的使用"><span class="nav-number">3.</span> <span class="nav-text">二、Web Workers的使用</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-实例化一个-Worker"><span class="nav-number">3.1.</span> <span class="nav-text">1. 实例化一个 Worker</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-数据通信"><span class="nav-number">3.2.</span> <span class="nav-text">2. 数据通信</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-错误处理机制"><span class="nav-number">3.3.</span> <span class="nav-text">3. 错误处理机制</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-终止-Worker"><span class="nav-number">3.4.</span> <span class="nav-text">4. 终止 Worker</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#三-Web-Workers的兼容"><span class="nav-number">4.</span> <span class="nav-text">三. Web Workers的兼容</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#四、Web-Workers支持的JavaScript特性"><span class="nav-number">5.</span> <span class="nav-text">四、Web Workers支持的JavaScript特性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#五、Web-Worker-的实践"><span class="nav-number">6.</span> <span class="nav-text">五、Web Worker 的实践</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#应用场景"><span class="nav-number">6.1.</span> <span class="nav-text">应用场景</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#1、数学运算"><span class="nav-number">6.1.1.</span> <span class="nav-text">1、数学运算</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2、图像处理"><span class="nav-number">6.1.2.</span> <span class="nav-text">2、图像处理</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3、大数据的处理"><span class="nav-number">6.1.3.</span> <span class="nav-text">3、大数据的处理</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#4-数据预处理"><span class="nav-number">6.1.4.</span> <span class="nav-text">4. 数据预处理</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#5-大量的-ajax-请求或者网络服务轮询"><span class="nav-number">6.1.5.</span> <span class="nav-text">5. 大量的 ajax 请求或者网络服务轮询</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Srtian</span>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js">
</script>
  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">102.8k</span>
  
</div>





        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
